package riteh.eventNetwork.client;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class ActivityProfile extends ListActivity {
	
	private ListView list;
	private ProfileEventsAdapter listAdapter;
	private Button buttonAdd;
	private Intent intentAdd, intentEditProfile, intentNotifications, intentSettings, intentAbout;
	private long userId;
	private String events[][];
	
/* ********************** OVERRIDE FUNCTIONS ******************************/	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(C.TAG, "PROFILE Activity");
		setContentView(R.layout.profile);
	
	// INSTANCIRANJE OBJEKTA
		buttonAdd = (Button) findViewById(R.id.profileButtonAdd);
		intentAdd = new Intent(this, ActivityEvent.class);
		intentEditProfile = new Intent(this, ActivityUserEdit.class);
		intentNotifications = new Intent(this, ActivityNotifications.class);
		intentNotifications.putExtra("userId", userId);
        intentSettings = new Intent(this, ActivitySettings.class);
        intentAbout = new Intent(this, ActivityAbout.class);

	// AKCIJE NA STARTU
		userId = this.getIntent().getExtras().getLong("userId");

		refresh();
		
		list = getListView();
		registerForContextMenu(list);
		
	// EVENT LISTENERS
		
		buttonAdd.setOnClickListener( new OnClickListener() {
			public void onClick(View v) {
				intentAdd.putExtra("userId", userId);
				startActivityForResult(intentAdd, C.ACTIVITY_EVENT);
			}
		});
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
    	Log.d(C.TAG,"PROFILE: onActivityResult: request: " + requestCode + ", result: " + resultCode);

		switch (requestCode) {
		case C.ACTIVITY_EVENT:
			if (resultCode == 0) {
				getProfileEvents();
			}
			return;
		case C.ACTIVITY_USER_EDIT:
			return;
		}
	}
	
	
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = new MenuInflater(this);
		inflater.inflate(R.menu.long_click_profile_event, menu);
	}
	
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		View v = info.targetView;
		long selectionId = v.getId();
		switch (item.getItemId()) {
		case R.id.longClickProfileEventDelete:
			profileEventDelete(selectionId);
			return true;
		case R.id.longClickProfileEventUsers:
			profileEventUsers(selectionId);
			return true;
		}
		return false;
	}

	
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = new MenuInflater(this);
		inflater.inflate(R.menu.profile, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.profileMenuEditProfile:
			editProfile();
			return true;
		case R.id.profileMenuSettings:
			showSettings();
			return true;
		case R.id.profileMenuRefresh:
			refresh();
			return true;
		case R.id.profileMenuAbout:
			startActivity(intentAbout);
			return true;
		}
		return false;
	}
	
/* ********************** PRIVATE FUNCTIONS *******************************/
   
	private void refresh() {
		int numOfNotifications;
		numOfNotifications = getNumberOfNotifications();
		
		if (numOfNotifications > 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("You have " + numOfNotifications + " new notifications!")
			       .setCancelable(false)
			       .setPositiveButton("Show", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   startActivity(intentNotifications);
			           }
			       })
			       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
		}
		
		getProfileEvents();
	}
	
	private int getNumberOfNotifications() {
	 	Log.d(C.TAG, "PROFILE: getNumberOfNotification()");
	
	 	RestClient client = new RestClient(getString(R.string.serverMethodGetNumberOfNotifications));
		client.AddParam("userId", String.valueOf(userId));
	 	
	 	String result = C.getMethod0(client, getString(R.string.serverMethodGetNumberOfNotifications));
	 	if (C.resultSuccess(this, result, getString(R.string.toastGetNumberOfNotificationsError))) {
	 		return Integer.parseInt(result);
	 	}
	 	else return 0;
	}
	
	private void editProfile() {
		intentEditProfile.putExtra("userId", userId);
		intentEditProfile.putExtra("userInfoId", userId);
		startActivityForResult(intentEditProfile, C.ACTIVITY_CIRCLE_EDIT);
	}
	
	private void showSettings() {
		startActivity(intentSettings);
	}
	
	private void profileEventUsers(long eventId) {

		RestClient client = new RestClient(getString(R.string.serverMethodUsersWhoResponded));
		client.AddParam("eventId", String.valueOf(eventId));
		String result[][] = C.getMethod2(client, getString(R.string.serverMethodUsersWhoResponded));
		
		if (C.resultSuccess(this, result, getString(R.string.toastUsersWhoRespondedError))) {
			
			if (result[0][0].compareTo("0") == 0) return;
			
			final CharSequence[] items = new CharSequence[result.length];
			
			for (int i=0; i<result.length; i++) {
				items[i] = result[i][1] + " " + result[i][2];
			}
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Users who responded:");
			builder.setItems(items, null);
			AlertDialog alert = builder.create();
			alert.show();
		}
	}
	
	private void profileEventDelete(long eventId) {
		RestClient client = new RestClient(getString(R.string.serverMethodDeleteEvent));
		client.AddParam("userId", String.valueOf(userId));
		client.AddParam("eventId", String.valueOf(eventId));
		
		String result = C.getMethod0(client, getString(R.string.serverMethodDeleteEvent));
		
		if (C.resultSuccess(this, result, getString(R.string.toastDeleteEventError))) {
			C.toast(this, "Event deleted!",0);
			getProfileEvents();
		}

	}
	
	private void getProfileEvents() {
		Log.d(C.TAG, "PROFILE: getProfileEvents()");
		
		RestClient client = new RestClient(getString(R.string.serverMethodGetProfileEvents));
		client.AddParam("userId", String.valueOf(userId));
		String result[][] = C.getMethod2(client,"getProfileEvents");
		
		events = new String[0][0];
		
		if (C.resultSuccess(this, result,getString(R.string.toastProfileEventsError))) {
			if (result[0][0].compareTo("0") != 0) {
				events = new String[result.length][result[0].length];
				events = result;
			}
		}
		
		listAdapter = new ProfileEventsAdapter(this);
		setListAdapter(listAdapter);
	}
	
	private class ProfileEventsAdapter extends ArrayAdapter<String[]> {
		private final Activity context;

		public ProfileEventsAdapter(Activity context) {
			super(context, R.layout.profile_list, events);
			this.context = context;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = context.getLayoutInflater();
			View rowView = inflater.inflate(R.layout.profile_list, null, true);
			
			TextView title = (TextView) rowView.findViewById(R.id.profileListTitle);
			TextView priority = (TextView) rowView.findViewById(R.id.profileListPriority);
			TextView duration = (TextView) rowView.findViewById(R.id.profileListDuration);
			TextView responses = (TextView) rowView.findViewById(R.id.profileListResponses);
			
			rowView.setId(Integer.parseInt(events[position][0]));
			title.setText(events[position][1]);
			duration.setText(events[position][2]);
			priority.setText(events[position][3]);
			responses.setText(events[position][4]);

			return rowView;
		}
	}
}
